#import "BaseScrollViewController.h"
#import "MJRefresh.h"
#import "UIColor+HexColor.h"

@interface BaseScrollViewController ()

///上下拉的空间，继承与ScrollView 的均可
@property (strong, nonatomic) UIScrollView *cacheScrollView;

@property (strong, nonatomic) UIView *emptyView;

///空视图的偏移量
@property (assign, nonatomic) CGFloat offset;

//@property (assign, nonatomic ,readwrite) NSInteger startNumber;

@end

@implementation BaseScrollViewController{
    ///是否刷新
    BOOL isRefreshing;
    ///是否完成加载
    BOOL _isLoadFinish;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.startNumber = 1;
    // Do any additional setup after loading the view.
}

#pragma mark - Nav
///导航栏阴影
- (void)addNavigationShadow{
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.5)];
    line.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:line];
    line.layer.shadowColor = HEXCOLOR(@"999999").CGColor;
    line.layer.shadowOffset = CGSizeMake(0,3);
    line.layer.shadowOpacity = 1;
    line.layer.shadowRadius = 5;
    //    self.navigationController.navigationBar.layer.cornerRadius = 2.5;
}

///导航栏下的分割线
-(void)addSpliteLine{
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.5)];
    line.backgroundColor = HEXCOLOR(@"dedede");
    [self.view addSubview:line];
}

#pragma mark - MJRefresh
//初始化上下拉刷新
-(void)initMJRefresh:(UIScrollView *)scrollView{
    [self initHeadRefresh:scrollView];
    [self initFootRefresh:scrollView];
}

//初始下拉刷新
-(void)initHeadRefresh:(UIScrollView *)scrollView{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(mjHeadRefresh)];
    header.automaticallyChangeAlpha = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    scrollView.mj_header = header;
    self.cacheScrollView = scrollView;
}

//初始化上拉加载
-(void)initFootRefresh:(UIScrollView *)scrollView{
    //MJRefreshAutoNormalFooter *foot = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(mjFootRefresh)];
    MJRefreshAutoNormalFooter *foot = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(mjFootRefresh)];
    foot.stateLabel.hidden = YES;
    scrollView.mj_footer = foot;
    self.cacheScrollView = scrollView;
    // 设置了底部inset
    scrollView.contentInset = UIEdgeInsetsMake(0, 0, 30, 0);
    // 忽略掉底部inset
    scrollView.mj_footer.ignoredScrollViewContentInsetBottom = 30;
}

-(void)mjEndRefresh{
    [self.cacheScrollView.mj_header endRefreshing];
    [self.cacheScrollView.mj_footer endRefreshing];
}

-(void)mbShowToast:(NSString *)text{
    [self mjEndRefresh];
    [self mbShowToast:text onWindow:NO];
    if(self.startNumber == 1 && self.loadingHelp && (!self.loadingHelp.isHidden) && !isRefreshing){
        [self yoShowEmpty:(LoadingHelpTypeErrorData)];
    }
}

-(void)openHeadRefresh{
    [self.cacheScrollView.mj_header beginRefreshing];
}

///下拉的回调
-(void)mjHeadRefresh{
    [self mbShowLoading];
    _startNumber = 1;
    isRefreshing = YES;
    [self httpRequestData];
}

//上拉加载的回调
-(void)mjFootRefresh{
    if (_isLoadFinish) {
        [self.cacheScrollView.mj_footer endRefreshing];
        return;
    }
    [self mbShowLoading];
    [self httpRequestData];
}


#pragma mark - 数据处理
///请求数据的方法
-(void)httpRequestData{
    
}


-(void)httpDataRequestFinish{
    [self httpDataRequestFinish:nil];
}

///加载完成后解析数据用的
-(void)httpDataRequestFinish:(NSMutableArray * _Nullable )data{
    [self mjEndRefresh];
    if (self.loadingHelp != nil) {
        [self yoDismiss];
    }
    
    [self mbDismiss];
    
    if (isRefreshing) {
        [self.dataArr removeAllObjects];
        isRefreshing = NO;
    }
    if (data) {
        [self.dataArr addObjectsFromArray:data];
        if (self.dataArr.count == 0) {
            [self showEmptyView];
        }else{
            [self dismissEmptyView];
        }
        [self dataLoadingFinish:data];
    }
    if ([self.cacheScrollView isKindOfClass:[UITableView class]]) {
        UITableView *t = (UITableView *)self.cacheScrollView;
        [t reloadData];
    }
    if ([self.cacheScrollView isKindOfClass:[UICollectionView class]]) {
        UICollectionView *c = (UICollectionView *)self.cacheScrollView;
        [c reloadData];
    }
    [self httpListLoadFinish];
}

-(void)httpDataRequestFinish:(NSMutableArray * _Nullable )data loadFinish:(BOOL)success isNetwork:(BOOL)isNetError err:(NSString *)err{
    if (success) {
        [self httpDataRequestFinish:data];
    }else{
        [self mjEndRefresh];
        if(self.startNumber == 1 && self.loadingHelp && !isRefreshing){
            if (isNetError) {
                [self yoShowEmpty:(LoadingHelpTypeNetWorkBtn)];
                return;
            }else{
                [self yoShowEmpty:(LoadingHelpTypeErrorData)];
                return;
            }
        }
        [self mbShowToast:err];
    }
}


///集成化所有判断，传进所有参数可以不用管刷新交互的一些逻辑
-(void)httpDataRequestFinish:(NSMutableArray * _Nullable )data loadFinish:(BOOL)success err:(NSString *)err{
    [self httpDataRequestFinish:data loadFinish:success isNetwork:NO err:err];
}

-(void)dataLoadingFinish:(NSArray *)arr{
    if (arr.count <= 0) {
        _isLoadFinish = YES;
        [self.cacheScrollView.mj_footer endRefreshingWithNoMoreData];
        if(self.dataArr.count == 0 && arr.count == 0){
            self.cacheScrollView.mj_footer.hidden = YES;
        }else{
            self.cacheScrollView.mj_footer.hidden = NO;
        }
        return;
    }
    if (arr.count != 0) {
        //        _startNumber += 10;
        _startNumber++;
    }
    self.cacheScrollView.mj_footer.hidden = NO;
    _isLoadFinish = NO;
}


-(void)httpListLoadFinish{
    if (self.dataArr.count == 0) {
        [self yoShowEmpty:(LoadingHelpTypeNormal)];
    }else{
        [self yoDismiss];
    }
}


#pragma mark - loadinghelp 挡板功能
///网络问题重新加载
-(void)yoLoadingErrorReload{
    [self yoShowLoading];
    [self httpRequestData];
}


#pragma mark - empty View
-(void)initEmptyView:(UIView *)empty{
    if (!empty) {
        UIImageView *img = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 0, 100, 100))];
        img.contentMode = UIViewContentModeScaleAspectFit;
        img.image = [UIImage imageNamed:@"noDate"];
        _emptyView = img;
    }else{
        _emptyView = empty;
    }
    
    self.offset = 0;
}

-(void)initEmptyView:(UIView *)empty withOffset:(CGFloat)offsect{
    _emptyView = empty;
    self.offset = offsect;
}

///空界面按钮点击事件
-(void)yoEmptyClick{
    [self openHeadRefresh];
}

-(void)showEmptyView{
    CGPoint center = self.cacheScrollView.center;
    _emptyView.center = CGPointMake(center.x, center.y + self.offset);
    [self.cacheScrollView addSubview:_emptyView];
}

-(void)dismissEmptyView{
    if (_emptyView) {
        [self.emptyView removeFromSuperview];
    }
}

-(void)emptyShowOrDismiss{
    if (self.dataArr.count == 0) {
        [self showEmptyView];
    }else{
        [self dismissEmptyView];
    }
}

-(NSMutableArray *)dataArr{
    if (_dataArr == nil) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

@end
